package com.yangff.utils;

import lombok.RequiredArgsConstructor;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@RequiredArgsConstructor
public class RedisUtil {

    // 默认一天
    public final Integer DEFAULT_TIMEOUT = 60 * 60 * 24;

    // 短期五分钟
    public final Integer SHORT_TIMEOUT = 60 * 5;

    private final RedissonClient redissonClient;

    /**
     * 增加或更新缓存
     *
     * @param key   键
     * @param value 值
     */
    public void set(String key, Object value) {
        RBucket<Object> bucket = redissonClient.getBucket(key);
        bucket.set(value);
    }

    /**
     * 增加或更新缓存，并设置过期时间,以秒为单位
     *
     * @param key     键
     * @param value   值
     * @param timeout 过期时间（秒）
     */
    public void set(String key, Object value, long timeout) {
        RBucket<Object> bucket = redissonClient.getBucket(key);
        bucket.set(value, timeout, TimeUnit.SECONDS);
    }

    /**
     * 获取缓存
     *
     * @param key 键
     * @return 缓存值
     */
    public Object get(String key) {
        RBucket<Object> bucket = redissonClient.getBucket(key);
        return bucket.get();
    }

    /**
     * 删除缓存
     *
     * @param key 键
     */
    public void delete(String key) {
        redissonClient.getBucket(key).delete();
    }

    /**
     * 检查缓存中是否存在某个键
     *
     * @param key 键
     * @return 是否存在
     */
    public boolean hasKey(String key) {
        RBucket<Object> bucket = redissonClient.getBucket(key);
        return bucket.isExists();
    }

    /**
     * 获取缓存的过期时间
     *
     * @param key 键
     * @return 过期时间（秒）
     */
    public Long getExpire(String key) {
        return redissonClient.getBucket(key).remainTimeToLive();
    }

    /**
     * 设置缓存的过期时间
     *
     * @param key     键
     * @param timeout 过期时间
     * @param unit    时间单位
     */
    public void expire(String key, long timeout, TimeUnit unit) {
        redissonClient.getBucket(key).expire(timeout, unit);
    }
}